package com.service;

import java.util.Map;

import javax.jws.WebService;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.service.utils.XmlUtils;

@Component
@WebService(serviceName = "ServiceService", // 与接口中指定的name一致
		targetNamespace = "http://service.com/", // 与接口中的命名空间一致,一般是接口的包名倒
		endpointInterface = "com.service.ServiceDelegate" // 接口地址
)
public class Service implements ServiceDelegate {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${margo.service.forward}")
	private String forwardUrl;

	@Override
	public String csg_message(String data, String token) {

		logger.info(data);

		JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
		logger.info("forwardUrl:" + forwardUrl);
		Client client = clientFactory.createClient(forwardUrl);

		try {
			Object[] result = client.invoke("csgMessage", data, token, "vssid");
			String response = (String) result[0];
			String code = null;
			String message = null;
			String time = null;
			try {
				Map<String, Object> map = XmlUtils.xmlToMap(response);
				code = (String) map.get("code");
				message = (String) map.get("message");
				time = (String) map.get("time");
			} catch (Exception e) {
				logger.error("xml解析错误：", e);
			}

			Document document = DocumentHelper.createDocument();
			Element root = document.addElement("ROOT");
			root.addElement("CODE").setText(code);
			root.addElement("MESSAGE").setText(message);
			root.addElement("time").setText(time);

			return document.asXML();
		} catch (Exception e) {
			logger.error("", e);
		}
		return "操作异常";
	}

}
